package dice.sinanya.db.redis;

import dice.sinanya.entity.EntityTypeMessages;
import dice.sinanya.system.MessagesSystem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.HashMap;

import static dice.sinanya.db.tools.JedisUtil.closeJedis;
import static dice.sinanya.db.tools.JedisUtil.getJedis;
import static dice.sinanya.system.MessagesSystem.loginInfo;
import static dice.sinanya.tools.checkdata.CheckIsNumbers.isNumeric;
import static dice.sinanya.tools.makedata.Sender.sender;

public class GroupNode {
    private static final Logger logger = LogManager.getLogger(GroupNode.class.getName());

    public static boolean checkGroupNode(String groupId, EntityTypeMessages entityTypeMessages) {
        String qqId = String.valueOf(loginInfo.getLoginId());
        boolean result = true;
        Jedis jedis = getJedis(5);
        try {
            if (!jedis.exists(groupId)) {
                HashMap<String, String> botInfo = new HashMap<>();
                botInfo.put("botId", qqId);
                botInfo.put("version", makeVersion(MessagesSystem.VERSIONS));
                jedis.hset(groupId, botInfo);
                Thread.sleep(200);
                return checkGroupNode(groupId, entityTypeMessages);
            } else if (!String.valueOf(loginInfo.getLoginId()).equals(jedis.hget(groupId, "botId"))) {
                long otherVersion = Long.parseLong(jedis.hget(groupId, "version"));
                long myVersion = Long.parseLong(makeVersion(MessagesSystem.VERSIONS));
                if (myVersion > otherVersion) {
                    HashMap<String, String> botInfo = new HashMap<>();
                    botInfo.put("botId", qqId);
                    botInfo.put("version", makeVersion(MessagesSystem.VERSIONS));
                    jedis.hset(groupId, botInfo);
                    if (entityTypeMessages != null) {
                        sender(entityTypeMessages, "此版本更新,已优先抢占服务位，无需关闭原骰子，对方在下次骰点时将自动保持静默");
                    }
                }
                result = false;
            }
        } catch (Exception e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
            logger.error(e.getMessage(), e);
        } finally {
            closeJedis(jedis);
        }
        return result;
    }

    public static String makeVersion(String version) {
        version = version
                .replace(".", "")
                .replace("Alpha", "")
                .replace("Beta", "")
                .replace("Stable", "");
        if (isNumeric(version)) {
            return version;
        } else {
            return "0";
        }
    }
}
